var layer;
var form;
var table;
var treeSelect;
var treeTable;
var iconSelected;
var columnObjName = "column_meun";
var columnArray = ['mname','mid','code','isProject','url','iconCls'];
var interUrl = {
		select: $projectPath+'/sys/menu/selectTreeTable',
		save: $projectPath+'/sys/menu/save',
		del: $projectPath+'/sys/menu/delete',
		selectTreeAll: $projectPath+"/sys/menu/selectTreeAll",
		selectMenuRole: $projectPath+"/sys/menu/selectMenuRole",
		saveMenuRole: $projectPath+"/sys/menu/saveMenuRole",
		updateState: $projectPath+"/sys/menu/updateState",
}
/**	
 * layui 组件引入
 * @returns
 */
layui.use([ 'layer', 'form', 'table', 'jquery' , "treeSelect", "treeTable", "iconSelected"], function() {
	layer = layui.layer;
	form = layui.form;
	table = layui.table;
	treeSelect = layui.treeSelect;
	treeTable = layui.treeTable;
	iconSelected = layui.iconSelected;
	
	// 加载字典
    getDictLabel("is_project", "#isProject", "isProject", true);
    getDictLabel("home_state", "#homeState", "homeState", true);
    getDictLabel("use_state", "#state", "state", true);
    
	// 执行一个 table 实例
    var treeTablParam = treeTable.render({
		elem : '#data_table',
		id : 'data_table',
		url : interUrl.select, 
		height:'full-120',
		page: false,
		toolbar : '#toolberLeft',
		treeColIndex: 1,	// 树形图标显示在第几列
        treeSpid: 0,		// 最上级的父级id
        treeIdName: 'mid',	// id字段的名称
        treePidName: 'parentId',// pid字段的名称
        treeDefaultClose: false,// 是否默认折叠
        treeLinkage: true,		// 父级展开时是否自动展开所有子级
		cols : [[
			{type : 'checkbox', fixed : 'left', hide: true},  
			{field : 'mname', title : '菜单名称', align : 'center', width: '200', hide: setColumnHide("mname")},
			{field : 'mid', title : 'ID', align : 'center', width: '80', hide: setColumnHide("mid")}, 
			{field : 'code', title : '编码', align : 'center', width: '100', hide: setColumnHide("code")}, 
			{field : 'state', title : '状态', align : 'center', width: '100', hide: setColumnHide("state"), toolbar : '#switchRow'}, 
			{field : 'isProject', title : '权限', align : 'center', width: '100', hide: setColumnHide("isProject"), templet: (d) => getDictText("is_project",d.isProject)}, 
			{field : 'url', title : '路由', align : 'center', width: '300', hide: setColumnHide("url")}, 
			{field : 'iconCls', title : '图标样式', align : 'center', width: '150', hide: setColumnHide("iconCls"),
				templet:function(res){
					return '<i class="'+res.iconCls+'"></i>';
				}
		    },{fixed : isRight(), title : '操作', align : 'center', width: '350', toolbar : '#toolRow'} 
		]]
	});
    
	// 头部左侧事件
    table.on('toolbar(data_table)',  function(obj) {
		if (obj.event === 'search') {
			method.laodTreeTabl();
		}else if(obj.event === 'add'){
			openWindowRB('data_form', '菜单添加', '500px', '100%', false, 0, false, false, null, 0.2, false, function(){
				loadTreeMeun(0);// 下拉树形菜单
				initIconSel()
			});
		}else if(obj.event === 'expand'){
			treeTable.expandAll('#data_table');
		}else if(obj.event === 'fold'){
			treeTable.foldAll('#data_table');
		}
	})
	
	// 函数对象
	var method = {
    	laodTreeTabl: function(){
    		var name = $("#serarch_name").val();
			treeTablParam.where = {"mname": name};
			treeTablParam = treeTable.render(treeTablParam);
			setTimeout(function(){
				$("#serarch_name").val(name);
			},500)
    	}
    }
    
	// 监听行工具事件
	table.on('tool(data_table)', function(obj) {
		var data = obj.data;
		if (obj.event === 'add') {
			openWindowRB('data_form', '菜单添加', '500px', '100%', false, 0, false, false, null, 0.2, false, function(){
				loadTreeMeun(data.mid);
			});
		}else if (obj.event === 'del') {
			deleteRow(table, 'data_table', {'mid':data.mid}, interUrl.del, function(res){
				if (res.success) {
					method.laodTreeTabl();
		        }
			});
		}else if (obj.event === 'edit') {
			openWindowRB('data_form', '菜单编辑', '500px', '100%', false, 0, false, false, data, 0.2, false, function(res){
				loadTreeMeun(data.parentId);
				initIconSel(res.iconCls)
			});
		}else if (obj.event === 'detail') {
			openWindowRB('data_form', '菜单查看', '500px', '100%', false, 0, false, false, data, 0.2, false, function(res){
				loadTreeMeun(data.parentId);
				initIconSel(res.iconCls)
			});
		}else if (obj.event === 'power') {
			openWindowRB('role_menu_form', '授权角色', '500px', '100%', false, 0, false, false, data, 0.2, false, function(res){
				table.render({
				    elem: '#role_menu_table',
				    id: 'role_menu_table',
				    url:  interUrl.selectMenuRole+'?mid=' + res.mid,
				    height:'full-230',
				    page: false,
				    cols: [[
				        {type: 'checkbox', fixed: 'left'},
				        {field: 'rname', width: 100, title: '角色名称'},
				        {field: 'state', width: 85, title: '状态', templet: (d) => getDictText("use_state", d.state, 1)},
				        {field: 'type', width: 90, title: '类型'},
				        {field: 'remarks', width: 150, title: '备注'}
				    ]]
				    ,done:function(result,currPage,count){//数据回调方法
				        var data = result.data;
				        data.forEach(function(o, i) {
				            if(o.rmstate > 0){
				                // 没有开启浮动使用这个即可
				                // $('div[lay-id="app-from"] .layui-table-body tr[data-index='+i+'] .layui-form-checkbox').click();
				                // 开启左浮动使用这个
				                $('div[lay-id="role_menu_table"] .layui-table-fixed tr[data-index='+i+'] .layui-form-checkbox').click();                                  
				            }
				        })
				    },
				});

			});
		}
	});
	
    // 提交角色菜单
	form.on('submit(roleMenuForm)', function(data) {
		var mid = data.field.mid;
		var check = table.checkStatus('role_menu_table');
	    var rids = [];
	    $(check.data).each(function (i, o) {// o 即为表格中一行的数据
	    	rids.push(o.rid);
	    });
	    var text = sbumitLoading('#role_menu_form .lay-submit-btn');
	    getAjax(interUrl.saveMenuRole, {rids: rids.join(","), mid: mid}, 'post', function (res) {
	        if (res.success) {
	            layer.closeAll();
	        }
	        showTips(res.msg);
	        closeLoading('#role_menu_form .lay-submit-btn', text)
	    })
	    return false;
	})
    
	// 提交
	form.on('submit(submitForm)', function(data) {
		saveData(table, 'data_table', data.field, interUrl.save, '#data_form ', function(res){
			if (res.success) {
				method.laodTreeTabl();
	        }
		});
		return false;
	})
	
	// 开关
	form.on('switch(stateSwitch)', function(data) {
		var mid = $(this).attr('mid');
	    var state = data.elem.checked?"0":"1";
	    getAjax(interUrl.updateState, {mid: mid, state: state}, 'post', function (res) {
	        showTips(res.msg);
	    })
		return false;
	})
	
})

/**
 * 初始化图标选择器--------------------------------------------------------------------------------
 */
function initIconSel(icon){
	$(".layui-ext-icon-selected-input").remove();
	$(".layui-ext-icon-selected-container").remove();
	iconSelected.render("#iconCls", {value: icon});
}


/**
 * 获取所有菜单-树形-------------------------------------------------------------------------------
 */
function loadTreeMeun(id){
	treeSelect.destroy('parentTree');
	// 参考：https://wujiawei0926.gitee.io/treeselect/docs/doc.html
	treeSelect.render({
        elem: '#parentTree',
        data:  interUrl.selectTreeAll,
        type: 'get',
        placeholder: '请选择菜单',
        search: true,
        style: {
            folder: {
                enable: false // 图标
            },
            line: {
                enable: true  // 线
            }
        },
        click: function(d){
            console.log(d);
        },
        success: function (d) {
        	// 选中节点，根据id筛选
    		treeSelect.checkNode('parentTree', id);
        	// 刷新树结构
        	treeSelect.refresh('parentTree');
        }
    });
}



